package handle

import (
	"encoding/xml"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"net/url"
	"time"
)

type WxHandleService struct {
}

// 微信回复消息结构
type WXRepTextMsg struct {
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      string
	// 若不标记XMLName, 则解析后的xml名为该结构体的名称
	XMLName xml.Name `xml:"xml"`
}

// ReplyWXMsg  微信自定义模板消息回复
func (w WxHandleService) GptReplyWXMsg(c *gin.Context, fromUser, toUser, usercontent string, accessToken *string) {
	//定义post的url地址
	URL := "https://bot.masterkagami.com/post"
	// 准备POST请求的数据
	formData := url.Values{
		"usermsg": {usercontent},
	}
	// 发送POST请求
	resp, err := http.PostForm(URL, formData)
	if err != nil {
		log.Println("Error sending POST request:", err)
		return
	}
	defer resp.Body.Close()
	respbody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("Error to read the response body", err)
		return
	}
	//输出响应内容
	log.Println(string(respbody))

	repTextMsg := WXRepTextMsg{
		ToUserName:   toUser,
		FromUserName: fromUser,
		CreateTime:   time.Now().Unix(),
		MsgType:      "text",
		Content:      string(respbody),
	}

	msg, err := xml.Marshal(&repTextMsg)
	if err != nil {
		log.Printf("[ERROR] - 将对象进行XML编码出错: %v\n", err)
		return
	}
	_, _ = c.Writer.Write(msg)
}

// 简单的消息推送
func (w WxHandleService) SimpleReply(c *gin.Context, fromUser, toUser, text string) {
	repTextMsg := WXRepTextMsg{
		ToUserName:   toUser,
		FromUserName: fromUser,
		CreateTime:   time.Now().Unix(),
		MsgType:      "text",
		Content:      text,
	}

	msg, err := xml.Marshal(&repTextMsg)
	if err != nil {
		log.Printf("[ERROR] - 将对象进行XML编码出错: %v\n", err)
		return
	}
	_, _ = c.Writer.Write(msg)
}
